package gmail_test;

import java.io.File;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.ElementNotVisibleException;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.ITestResult;
import org.testng.annotations.*;



public class BasicTestCase {

	
	protected static EventFiringWebDriver driver;
	
	protected WebDriver getWebDriver()
	{
		WebDriver webDriver = null;
		TestLogger logger = new TestLogger();
		
		if(webDriver==null)
		{
			webDriver = new FirefoxDriver();
			// webDriver = new InternetExplorerDriver();
			webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
		}
		
		driver = new EventFiringWebDriver(webDriver);
		driver.register(logger);
		
		return driver;
	}
	
	protected void WaitElementOnPage(WebElement element)
	{
		//driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
		
		WebDriverWait wait = new WebDriverWait(driver, 1, 1000);
		wait.withMessage("Element was not found");
		wait.ignoring(StaleElementReferenceException.class, ElementNotVisibleException.class);
		
		wait.until(ExpectedConditions.visibilityOf(element));
	}
	
	@AfterTest
	public void treaDown() throws Exception
	{
		driver.close();		
	}
	
	@BeforeTest
	public void beforeTest() throws Exception
	{
		//delete all screenshots in folder
		try
		{
			File[] files = (new File("Screenshots")).listFiles();
			for (File f : files)
				f.delete();
		}
		catch (Exception e)	{}
	}
	
	@AfterMethod(alwaysRun=true)
	public void TryLogOut(ITestResult m) throws Exception
	{
		try
		{
			HomePage homePage = PageFactory.initElements(driver, HomePage.class);
			homePage.logOut();
		}
		catch(Exception e){}
	
	}
	
	 public String origStyle;
	 public void highlight(WebElement element, WebDriver driver){
		 	origStyle= element.getAttribute("style");
	        JavascriptExecutor executor = (JavascriptExecutor)driver;
	        executor.executeScript("arguments[0].setAttribute(arguments[1], arguments[2])", element, "style", "border: 2px solid red; color: red;");
	        
	        try{
	            Thread.sleep(500); 
	        }catch (InterruptedException e){
	            //ignore
	        }
	        executor.executeScript("arguments[0].setAttribute(arguments[1], arguments[2])", element, "style", origStyle);
	    }
	 
	 
}
